using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections;
using System.Collections.Generic;

namespace QQZiFramework
{
    public class MyMemoryCache : IMemoryCache
    {
        private readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
        private readonly List<object> _keys = new List<object>();

        public ICacheEntry CreateEntry(object key)
        {
            _keys.Add(key);
            return _cache.CreateEntry(key);
        }

        public void Remove(object key)
        {
            _cache.Remove(key);
            _keys.Remove(key);
        }

        public bool TryGetValue(object key, out object value)
        {
            return _cache.TryGetValue(key, out value);
        }

        public void Clear()
        {
            foreach (var key in _keys)
            {
                _cache.Remove(key);
            }
            _keys.Clear();
        }

        public void Dispose()
        {
            _cache.Dispose();
        }

        public void RemoveByKey(object key)
        {
            _cache.Remove(key);
            _keys.Remove(key);
        }

        public void RemoveLike(string keyPatten)
        {
            foreach (string key in _keys)
            {
                if (key.IndexOf(keyPatten) > -1)
                {
                    Remove(key);
                }
            }
        }

        public bool TryGetValueByKey(object key, out object value)
        {
            return _cache.TryGetValue(key, out value);
        }

        // 其他 IMemoryCache 接口方法实现
        public bool TryGetValue<TItem>(object key, out TItem value)
        {
            var result = _cache.TryGetValue(key, out object obj);
            value = (TItem)obj;
            return result;
        }

        public ICacheEntry CreateEntry<TItem>(object key)
        {
            _keys.Add(key);
            return _cache.CreateEntry(key);
        }


        
    }
}